import { getSetting, chooseAddress, openSetting, showModal, showToast } from "../../utils/asyncWx.js"
import regeneratorRuntime from '../../lib/runtime/runtime';

Page({
  data: {
    address: {},
    cart: {},
    // 控制全选
    allChecked: false,
    //总价格
    totalPrice: 0,
    // 总数量
    totalNum: 0
  },
  //当页面显示的时候触发
  onShow () {
    //获取本地的address
    const address = wx.getStorageSync('address');
    // 获取缓存中的购物车数据
    this.setData({
      address
    })
    let cart = wx.getStorageSync('cart') || [];
    this.setCart(cart)
  },
  // 点击获取收货地址的按钮
  async handleChooseAddress () {
    try {
      //  1.获取权限状态
      const result = await getSetting()
      // 获取收获地址的权限状态
      const scopeAddress = result.authSetting["scope.address"]
      // 曾经拒绝过授权，先诱导用户打开授权 opensetting
      if (scopeAddress === false) {
        await openSetting()
      }
      const address = await chooseAddress()
      // 将地址保存在本地storage中
      wx.setStorage({
        key: 'address',
        data: address
      });

    } catch (error) {
      console.log(error);
    }
  },
  // 商品复选框事件
  handleItemChange (e) {
    // 获取要被修改的商品的id
    const goods_id = e.currentTarget.dataset.id;
    // 获取购物车数组
    let cart = this.data.cart
    // 找到要修改的商品对象，根据findIndex方法
    const index = cart.findIndex(item => item.goods_id === goods_id)
    // 取反
    cart[index].checked = !cart[index].checked

    this.setCart(cart)

  },
  // 根据购物车对象计算价格、总数、全选
  setCart (cart) {
    let totalPrice = 0
    let totalNum = 0
    let allChecked = true
    cart.forEach(item => {
      if (item.checked) {
        totalPrice += item.goods_price * item.num
        totalNum += item.num
      }
      else {
        allChecked = false
      }
    });
    // 判断数组是否为空
    allChecked = cart.length === 0 ? false : allChecked

    this.setData({
      cart,
      allChecked,
      totalPrice,
      totalNum
    })
    wx.setStorageSync('cart', cart);
  },
  // 全选/取反
  handleItemAllChecked () {
    // 1. 获取data中的数据
    let { cart, allChecked } = this.data
    allChecked = !allChecked
    cart.forEach(item => {
      // 将所有选中状态和allchecked一致
      item.checked = allChecked
    })
    this.setCart(cart)
  },
  //商品数量的编辑
  async handleItemNumEdit (e) {
    // 获取商品id和操作数
    const { id: goods_id, operation } = e.currentTarget.dataset
    // 获取购物车的数组
    let cart = this.data.cart
    // 根据id获取到索引
    const index = cart.findIndex(item => item.goods_id === goods_id)
    // cart[index].num += operation
    // if(cart)
    // 当商品数量为1时点击 - 询问是否删除
    if (cart[index].num == 1 && operation === -1) {
      const res = await showModal({ content: "确定删除商品？" })
      if (res.confirm) {
        cart.splice(index, 1)
        this.setCart(cart)
      }
    }


    else {
      cart[index].num += operation
      this.setCart(cart)
    }

  },
  //点击了结算按钮
  async handlePay () {
    // 1. 判断收获地址
    const address = this.data.address
    const cart = this.data.cart
    if (!address) {
      return await showToast({
        title: '请选择收货地址',
        icon: 'none'
      });

    }
    if (cart.length === 0) {
      return await showToast({
        title: '请选择商品',
        icon: 'none'
      });

    }
    // 跳转界面
    wx.navigateTo({
      url: '/pages/pay/index'
    });



  }
})